package cn.jinbyte.starter.web.config;

import cn.jinbyte.web.config.ApiLogProperties;
import cn.jinbyte.web.dao.ApiLogDao;
import cn.jinbyte.web.filter.ApiLogFilter;
import cn.jinbyte.web.interceptor.ApiLogInterceptor;
import lombok.RequiredArgsConstructor;
import org.jetbrains.annotations.NotNull;
import org.springframework.boot.autoconfigure.condition.ConditionalOnMissingBean;
import org.springframework.boot.autoconfigure.condition.ConditionalOnProperty;
import org.springframework.context.annotation.Bean;
import org.springframework.web.servlet.config.annotation.InterceptorRegistry;
import org.springframework.web.servlet.config.annotation.WebMvcConfigurer;

import static cn.jinbyte.starter.web.config.StarterConst.CONF_PREFIX;


@RequiredArgsConstructor
@ConditionalOnProperty(prefix = CONF_PREFIX + ".api-log", name = "enabled", havingValue = "true", matchIfMissing = true)
public class ApiLogConfig implements WebMvcConfigurer {

    private final ApiLogProperties properties;

    private final ApiLogDao logDao;


    @Bean
    @ConditionalOnMissingBean
    public ApiLogFilter apiLogFilter() {
        return new ApiLogFilter(properties);
    }

    /**
     * 添加接口日志拦截器
     *
     * @param registry 拦截器注册器
     */
    @Override
    public void addInterceptors(@NotNull InterceptorRegistry registry) {
        // 注册接口日志拦截器
        registry.addInterceptor(new ApiLogInterceptor(properties, logDao))  // 实际会由Spring注入，这里null不影响
                .addPathPatterns("/**")  // 根据需要调整拦截路径
                .excludePathPatterns(properties.getExcludePatterns());  // 排除不需要拦截的路径
    }
}

